<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--分类数据-->
      <el-col :span="4" :xs="15">
        <div class="head-container">
          <el-input
            v-model="categoryName"
            placeholder="请输入分类名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="categoryOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--模型数据 -->
      <el-col :span="20" :xs="24">
        <!--模型搜索框表单-->
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="模型名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-form>

        <!--流程模型列表-->
        <el-table v-loading="loading" fit :data="definitionList" >
          <el-table-column label="流程名称" align="center" width="120" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-button v-if="scope.row.id && scope.row.modelState!=1" type="text" @click="handleReadImage(scope.row.id)">
                <span>{{ scope.row.name }}</span>
              </el-button>
              <span v-else>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="流程分类" align="center" prop="categoryName"/>
          <el-table-column label="流程版本" align="center">
            <template slot-scope="scope" v-if="scope.row.version">
              <el-tag size="medium">v{{ scope.row.version }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="发布时间" align="center" prop="publishTime" width="180"/>
          <el-table-column label="操作" width="250" fixed="right" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button @click="startModel(scope.row)" icon="el-icon-check" type="primary"
                         size="small">发起流程
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 流程图 -->
    <el-dialog :title="readImage.title" :visible.sync="readImage.open" width="70%" append-to-body>
      <!-- <el-image :src="readImage.src"></el-image> -->
      <flow :flowData="flowData"/>
    </el-dialog>

    <!--发起表单-->
    <el-dialog :title="startFormTitle" :visible.sync="formStartOpen" width="50%" append-to-body>
      <div class="test-form">
        <parser :key="new Date().getTime()" :form-conf="formConf" @submit="submitForm" ref="parser" @getData="getData" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import IconSelect from "@/components/IconSelect";
import {
  addDeployment,
  updateDeployment,
  exportDeployment,
  definitionStart,
} from "@/api/flowable/definition";
import {
  listModel,addModel,delModel,publishModel,getModelXML,suspensionModelState,getModelStartForm
} from "@/api/process/model";
import {
  startProcess
} from "@/api/process/ins";
import {treeCategorySelect} from "@/api/process/category";
import {getToken} from "@/utils/auth";
import {getForm, addDeployForm, listForm} from "@/api/process/form";
import Parser from '@/components/parser/Parser'
import flow from '@/views/flowable/task/myProcess/send/flow'
import category from "../../process/category/index.vue";
import Treeselect from "@riophae/vue-treeselect";
import Model from '../../flowable/definition/model';
export default {
  name: "Start",
  computed: {
    category() {
      return category
    }
  },
  dicts: ['sys_process_category'],
  components: {
    Treeselect,
    IconSelect,
    Parser,
    flow,
    Model,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      dialogVisible: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 流程定义表格数据
      definitionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      formStartOpen: false,
      startFormTitle: "",
      formDeployOpen: false,
      formDeployTitle: "",
      // 分类名称
      categoryName: undefined,
      // 分类树选项
      categoryOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      formList: [],
      formTotal: 0,
      formConf: {}, // 默认表单数据
      // 模型详情
      modelDetails: {
        open: false,
        src: "",
      },
      readImage: {
        open: false,
        src: "",
      },
      // bpmn.xml 导入
      upload: {
        // 是否显示弹出层（xml导入）
        open: false,
        // 弹出层标题（xml导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        name: null,
        category: null,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/flowable/definition/import"
      },
      // 查询参数
      queryParams: {
        formName: null,
        pageNum: 1,
        pageSize: 10,
        name: null,
        categoryId: null,
        category: null,
        key: null,
        tenantId: null,
        deployTime: null,
        derivedFrom: null,
        derivedFromRoot: null,
        parentDeploymentId: null,
        engineVersion: null
      },
      formQueryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 挂载表单到流程实例
      formDeployParam: {
        id: null,
        deployId: null
      },
      deployId: '',
      currentRow: null,
      // xml
      flowData: {},
      // 表单参数
      form: {},
      // 表单选项
      formOptions: [],
      // 启动表单ID
      startFormId: null,
      // 发起流程的模型ID
      id: null,
      // 表单校验
      rules: {
        name: [
          {required: true, message: "模型名称不能为空", trigger: "blur"}
        ],
        categoryId: [
          {required: true, message: "分类不能为空", trigger: "blur"}
        ],
      }
    };
  },
  watch: {
    // 根据名称筛选树
    categoryName(val) {
      console.log(val)
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getCategoryTree();
  },
  activated() {
    const time = this.$route.query.t;
    if (time != null) {
      this.getList();
    }
  },
  methods: {
    /** 接收子组件传的值 */
    getData(data) {
      if (data) {
        const variables = [];
        data.fields.forEach(item => {
          let variableData = {};
          variableData.label = item.__config__.label
          // 表单值为多个选项时
          if (item.__config__.defaultValue instanceof Array) {
            const array = [];
            item.__config__.defaultValue.forEach(val => {
              array.push(val)
            })
            variableData.val = array;
          } else {
            variableData.val = item.__config__.defaultValue
          }
          variables.push(variableData)
        })
        this.variables = variables;
      }
    },
    // 发起流程
    startModel(row){
      // 查询表单
      this.formStartOpen=true;
      let id =row.id;// 模型ID
      this.id=id;
      getModelXML(id).then(res => {
        this.flowData = res.data;
      })
      getModelStartForm(id).then(res => {
        // 流程过程中不存在初始化表单 直接读取的流程变量中存储的表单值
        this.formConf = res.data;
      }).catch(res => {
        this.goBack();
      })
    },
    /** 返回页面 */
    goBack() {
      // 关闭当前标签页并返回上个页面
      const obj = { path: "/flowable/my", query: { t: Date.now()} };
      this.$tab.closeOpenPage(obj);
    },
    // 选择图标
    selected(name) {
      this.form.icon = name;
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.categoryId = data.id;
      this.handleQuery();
    },
    /** 查询分类下拉树结构 */
    getCategoryTree() {
      treeCategorySelect().then(response => {
        this.categoryOptions = response.data;
      });
    },
    /** 查询流程定义列表 */
    getList() {
      this.loading = true;
      listModel(this.queryParams).then(response => {
        this.definitionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleClose(done) {
      this.$confirm('确定要关闭吗？关闭未保存的修改都会丢失？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        done();
      }).catch(() => {
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        category: null,
        key: null,
        tenantId: null,
        deployTime: null,
        derivedFrom: null,
        derivedFromRoot: null,
        parentDeploymentId: null,
        engineVersion: null,
        icon: undefined,
        formId: null,
        formOptions: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 流程图查看 */
    handleReadImage(id) {
      this.readImage.title = "流程图";
      this.readImage.open = true;
      // this.readImage.src = process.env.VUE_APP_BASE_API + "/flowable/definition/readImage/" + deploymentId;
      getModelXML(id).then(res => {
        this.flowData = res.data;
      })
    },
    /** 详情查看 */
    handleModelDetail(row){
      this.modelDetails.title = "详情";
      this.modelDetails.open = true;
    },
    /** 表单查看 */
    handleForm(id) {
      getForm(id).then(res => {
        this.formTitle = "表单详情";
        this.formConfOpen = true;
        this.formConf = JSON.parse(res.data.content)
      })
    },
    /** 启动流程 */
    handleDefinitionStart(row) {
      definitionStart(row.id).then(res => {
        this.$modal.msgSuccess(res.msg);
      })
    },
    // /** 更改挂载表单弹框 */
    // handleEditForm(row){
    //   this.formDeployParam.deployId = row.deploymentId
    //   const queryParams = {
    //     pageNum: 1,
    //     pageSize: 10
    //   }
    //   listForm(queryParams).then(res =>{
    //     this.formList = res.rows;
    //     this.formDeployOpen = true;
    //     this.formDeployTitle = "挂载表单";
    //   })
    // },
    /** 申请流程表单数据提交 */
    submitForm(data) {
      const variables = data.valData; // 输入的表单值
      const formData = data.formData; // 表单
      formData.disabled = true; // 设置禁止修改
      formData.formBtns = false; // 隐藏按钮
      if (this.id) {
        variables.variables = formData; // 整个表单+输入数据 合并
        let requestData={}; // 请求参数
        requestData.modelId=this.id; // 模型ID
        requestData.variables=variables; // 变量及表单
        startProcess(requestData).then(res => {
          this.$modal.msgSuccess(res.msg);
          this.goBack();
        })
/*        if (this.taskForm.procDefId) {
          variables.variables = formData;
          // 启动流程并将表单数据加入流程变量
          definitionStart(this.taskForm.procDefId, JSON.stringify(variables)).then(res => {
            this.$modal.msgSuccess(res.msg);
            this.goBack();
          })
        }*/
      }
    },
  }
};
</script>
